from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
import json
from fake_useragent import UserAgent

import configparser
cp = configparser.ConfigParser()
cp.read('account.cfg')


def login(username, password):
    url = "https://passport.weibo.cn/signin/login?entry=mweibo&r=https%3A%2F%2Fweibo.cn%2F&backTitle=%CE%A2%B2%A9&vt="
    chrome_options = Options()
    # ua = UserAgent()
    # chrome_options.add_argument('user-agent={}'.format(ua.random))
    # chrome_options.add_argument('--headless')
    # prefs = {"profile.managed_default_content_settings.images": 2}
    # chrome_options.add_experimental_option("prefs", prefs)
    driver = webdriver.Chrome(chrome_options=chrome_options)
    driver.get(url)
    time.sleep(10)
    driver.maximize_window()
    # driver.find_element_by_xpath('//*[@id="pl_login_form"]/div/div[1]/div/a[1]').click()
    driver.find_element_by_id('loginName').clear()
    driver.find_element_by_id('loginPassword').clear()
    driver.find_element_by_id('loginName').send_keys(username)
    driver.find_element_by_id('loginPassword').send_keys(password)
    time.sleep(1)
    driver.find_element_by_id('loginAction').click()
    time.sleep(10)
    cookies_list = driver.get_cookies()
    # with open('wblogin.html','w',encoding='utf-8') as f:
    #   f.write(driver.page_source)
    driver.close()
    return cookies_list


if __name__ == '__main__':
    username = cp.get('weibo', 'USERNAME')
    password = cp.get('weibo', 'PASSWORD')
    cookies_list = login(username, password)
    print('Cookies获取成功...')
    with open('cookies/weibo(mb)_cookies.txt', 'w', encoding="utf-8") as f:
        f.write(json.dumps(cookies_list))
